#! /usr/bin/env python
# -*- coding: utf-8 -*-
#检测log size与前Times次取得的平均值的差是否大于(、等于或小于)阙值 Threshold
#zabbix items useage：log.change[LogFile,Times,Threshold,Operator]

import os,sys

#####
#logtmp={
#    dataList:[1,2,3,4,5,6,7,8,9,...],
#    flag:0..len(datalist)-1
#}
#####

#之前取值临时存放数据结构
log_tmp = {
    'datalist' : [],
    'flag' : 0
    }

##之前取值临时存放数据文件
TempFile="/tmp/Checklogsize.tmp"

#读写临时文件
class LogTmp:

    def __init__(self):
        self.conf = TempFile
        self.logtmp = log_tmp

    #写临时文件
    def Set(self,Value):
        with open(self.conf,"w") as F:
            F.write(str(Value))
        F.close()
        return

    #读临时文件
    def Get(self):
        with open(self.conf,"r") as F:
            tmp = ''.join(F.readlines())
        F.close()
        return eval( tmp )

    #检查临时文件是否已经存在
    def Check(self):
        return os.path.isfile(self.conf)

logtmp = LogTmp()

class CheckLogs:

    def __init__(self):
        if logtmp.Check() and logtmp.Get():
            self.logTmp = logtmp.Get()
        else:
            self.logTmp = logtmp.logtmp


    def CheckLog(self,LogFile,Times,Threshold,Operator):
        logsize = self.GetLogSize(LogFile)
        #print logsize
        diff = self.GetDiffSize(logsize,Times,Threshold)
        #print diff
        ret = self.Compare(diff,Operator)
        return ret

    #获取指定log的size大小
    def GetLogSize(self,LogFile):
        if os.path.isfile(LogFile):
            return os.path.getsize(LogFile)
        else:
            return "False"

    #取最新数据与Times次数据的平均值做比较，返回其差值Diff
    def GetDiffSize(self,Logsize,Times,Threshold):
        index = int(Times) - 1
        ret = 0
        dataList = self.logTmp['datalist']
        flag = self.logTmp['flag']
        if int(Times) == len(dataList):
            #times次记录的平均值
            avgSize = sum(dataList)/int(Times)
            #print avgSize
            #当前日志Size与平均值的变化值
            diff = Logsize - avgSize
            #print diff
            #变化值于阈值的差
            ret = diff - int(Threshold)
            dataList[flag] = Logsize
            if 0 <= flag < index:
                flag+=1
            elif flag == index:
                flag = 0
        else:
            dataList.append(Logsize)

        self.logTmp['datalist'] = dataList
        self.logTmp['flag'] = flag
        logtmp.Set(self.logTmp)
        print ret
        print str(self.logTmp)
        return ret

    #根据选定的判断方式，返回最终比较结果
    def Compare(self,Ret,Operator):
        equal = 0
        less = 0
        greater = 0
        if Operator == 1:
            greater = 1
        elif Operator == 2:
            equal = 1
        elif Operator == 3:
            less = 1
        if Ret ==0:
            return equal
        elif Ret <0:
            return less
        else:
            return greater

'''
LogFile:日志绝对路径
Times：平均值取值个数
Threshold：报警阈值
Operator：
    1：当前记录与平均值的变化值 大于阈值报警
    2：当前记录与平均值的变化值 等于阈值报警
    3：当前记录与平均值的变化值 小于阈值报警
'''
if __name__ == "__main__":
    if len(sys.argv) < 3:
        print "$0 LogFile Times Threshold (Operator=1)"
        exit()
    elif '2' in sys.argv[4] or '3' in sys.argv[4]:
        Operator = sys.argv[4]
    else:
        Operator = 1

    LogFile = sys.argv[1]
    Times = sys.argv[2]
    Threshold = sys.argv[3]
    ck = CheckLogs()
    ret = ck.CheckLog(LogFile,Times,Threshold,Operator)
    print ret
